<?php
/**
 * Created by PhpStorm.
 * User: iceberg
 * Date: 2019-01-27
 * Time: 13:56
 */

namespace app\service;

use app\model\Data;
use app\validate\DataValidate;
use think\Exception;
use think\facade\Request;
use think\facade\Env;

class DataService
{
    //分页
    public function page()
    {
        //获取request参数
        $request = Request::get();
        $name = isset($request['name']) ? $request['name'] : '';
        //封装where查询条件
        $where = [];
        empty($name)    ||  $where[]   = ['pname', 'like', '%'.$name.'%'];
        //拼接page参数
        $pageParam = ['query' => []];
        $pageParam['query']['name'] = $name;
        return Data::where($where)->order('id desc')->paginate(10, false, $pageParam);

    }

    //统计个数
    public function count()
    {
        return Data::count();
    }

    //保存数据
    public function save()
    {
        Request::isPost() || die('request not post!');
        //获取参数
        $param = Request::param();
        //是否通过验证
        $error = $this->_validate($param);
        //$error = null;
        if(is_null($error)){

            //压缩包上传
            //$file = Request::file('file');
            try{
                $file = Request::file('file');
            }
            catch (Exception $e)
            {
                //判断是否上传文件
                return ajax_return(2,$e->getMessage());
            }
            //var_dump($file);die;
            // 上传压缩包验证
//            $result = $file->validate(['size' => 100000,'ext' => 'zip,rar']);
//            if(true !== $result){
//                return var_dump($result);
//            }
//            die;

            //移动到框架应用根目录/public/uploads/目录下
            $info = $file->rule(function($file){
                return date("Ymd") . '/' . date("YmdHis");//日期目录下，日期时间为文件名
            })->validate(['ext' => 'zip,rar'])->move(Env::get('root_path') . 'public' . '/' . 'uploads', true, false);// 移动到服务器的上传目录 并且设置不覆盖

//            var_dump($info);
//            die;
            if(!$info){
                return ajax_return(2,'文件上传类型错误，只支持zip,rar文件！');
            }
            if($info){
                //添加数据
                $fpath ='/uploads/' . $info->getSaveName();
                $param['fpath'] = $fpath;
//                var_dump($param);die;
                $data = new Data;
                //检测错误
                //allowField(true)过虑post数组中非数据表字段数据
                if( $data->allowField(true)->save($param) ){
                    return ajax_return(1, '保存成功');
                }else{
                    return ajax_return(2,'保存失败');
                }
            }
        }else{
            return ajax_return(2, $error);
        }
    }


    //删除
    public function delete($id)
    {
        Request::isPost() || die('request not post!');

        if(Data::destroy($id)){
            return ajax_return(0, '删除成功');
        }else{
            return ajax_return(100, '删除失败');
        }
    }

    //导出数据
    public function export()
    {

        //导出数据
        // excel表头
        $headArr[] = '项目名称';
        $headArr[] = '申报类型1';
        $headArr[] = '申报类型2';
        $headArr[] = '申报单位';
        $headArr[] = '联系人';
        $headArr[] = '联系电话';
        $headArr[] = '电子邮箱';
        $headArr[] = '通信地址';
        $headArr[] = '上传时间';
        $headArr[] = '资料下载';


        $list = Data::select();
        //var_dump($list);die;

        $dataSet = array();
        foreach($list as $data){
            // 获取申报资料数据
            $datatemp[0]=$data->pname;
            $datatemp[1]=config('rbac.PROJECT_TYPE')[$data->type1];
            $datatemp[2]=isset($data->type2) ? config('rbac.PROJECT_TYPE')[$data->type2] : '';
            $datatemp[3]=$data->unit;
            $datatemp[4]=$data->contact;
            $datatemp[5]=$data->phone;
            $datatemp[6]=$data->email;
            $datatemp[7]=$data->address;
            $datatemp[8]=$data->add_time;
            $datatemp[9]=Request::domain() . $data->fpath;


            $dataSet[] = $datatemp;
        }

        $filename = '申报资料信息表';

        if($dataSet){
            export_excel($filename, $headArr, $dataSet); // $filename excel名称 $headArr excel表头
        }

    }

    //根据id得到数据
    public function edit($id)
    {
        return Data::get($id);
    }

    //验证器
    private function _validate($data)
    {
        //验证
        $validate = new DataValidate();
        if(!$validate->check($data))
        {
            return $validate->getError();
        }
    }
}